package com.fitz.proxy;

import com.fitz.cluster.AbstractClusterStrategy;
import com.fitz.remote.model.RpcRequest;
import com.fitz.remote.model.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @author fitz 2020-5-11 20:35
 */
@Slf4j
public class RpcProxyInvocationHandler implements InvocationHandler {

    private RpcReferenceBean referenceBean;

    public RpcProxyInvocationHandler(RpcReferenceBean referenceBean) {
        this.referenceBean = referenceBean;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest rpcRequest = new RpcRequest();
        String requestId = UUID.randomUUID().toString().replace("-","");
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        Class<?>[] paramsType = method.getParameterTypes();
        rpcRequest.setRequestId(requestId);
        rpcRequest.setClassName(className);
        rpcRequest.setMethodName(methodName);
        rpcRequest.setParamsType(paramsType);
        rpcRequest.setParams(args);
        rpcRequest.setCreateTime(System.currentTimeMillis());
        rpcRequest.setTimeout(referenceBean.getTimeout());

        AbstractClusterStrategy strategy = referenceBean.getClusterStrategy();
        RpcResponse rpcResponse = strategy.call(rpcRequest,referenceBean);
        //利用netty发送请求到服务端
        log.debug("Final receive rpcResponse:{}",rpcResponse.toString());
        return rpcResponse.getResult();
    }
}
